package com.mmall.seckill.controller;

import com.mmall.seckill.common.CodeMsg;
import com.mmall.seckill.common.Const;
import com.mmall.seckill.common.Result;
import com.mmall.seckill.common.redis.RedisService;
import com.mmall.seckill.common.redis.keyCode.GoodsKey;
import com.mmall.seckill.domain.SeckillUser;
import com.mmall.seckill.service.GoodsService;
import com.mmall.seckill.vo.GoodsDetailVo;
import com.mmall.seckill.vo.GoodsVo;
import org.apache.catalina.servlet4preview.http.HttpServletRequest;
import org.apache.commons.lang3.StringUtils;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.thymeleaf.spring4.context.SpringWebContext;
import org.thymeleaf.spring4.view.ThymeleafViewResolver;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.util.List;

/**
 * Created by megan on 2018/6/17.
 * 商品模块
 */
@Controller
@RequestMapping("/goods/")
public class GoodsController {

    @Resource
    private GoodsService goodsService;
    @Resource
    private RedisService redisService;
    @Resource
    private ThymeleafViewResolver thymeleafViewResolver;
    @Resource
    private ApplicationContext applicationContext;


    @RequestMapping(value = "goods.page",produces = "text/html")
    @ResponseBody
    public String goodsPage2(Model model, SeckillUser user, HttpServletRequest request, HttpServletResponse response){
        // 从缓存里面去取页面
        String html = redisService.get(GoodsKey.getGoodsListKeyPage,Const.page.GOODS_LIST);
        if(StringUtils.isNotEmpty(html)){
            return html;
        }
        List<GoodsVo> goodsList = goodsService.listGoodsVo();
        model.addAttribute("user", user);
        model.addAttribute("goodsList",goodsList);
        SpringWebContext ctx = new SpringWebContext(request,response,request.getServletContext(),request.getLocale(),model.asMap(),applicationContext);
        if(user == null){
            return  thymeleafViewResolver.getTemplateEngine().process(Const.page.LOGIN_PAGE,ctx);
        }
        // 没有取到页面，手动渲染页面
        html = thymeleafViewResolver.getTemplateEngine().process(Const.page.GOODS_LIST,ctx);
        if(StringUtils.isNotEmpty(html)){
            // 得到渲染后的模板，保存到redis里面,缓存60秒
            redisService.setEx(GoodsKey.getGoodsListKeyPage,Const.page.GOODS_LIST,html,GoodsKey.getGoodsListKeyPage.expireSeconds());
        }
        return html;
    }


    /**
     * 秒杀详情
     * @param model
     * @param goodsId
     * @param user
     * @return
     */
    @RequestMapping(value = "detail2.page/{goodsId}",method = RequestMethod.GET,produces = "text/html")
    @ResponseBody
    public String detailPage2(Model model,@PathVariable long goodsId,SeckillUser user,HttpServletRequest request, HttpServletResponse response){
        GoodsVo goods = goodsService.getGoodsVoByGoodsId(goodsId);
        long startAt = goods.getStartDate().getTime();
        long endAt = goods.getEndDate().getTime();
        GoodsDetailVo vo = getStatus(startAt,endAt);
        model.addAttribute("user",user);
        model.addAttribute("goods",goods);
        model.addAttribute("miaoshaStatus",vo.getMiaoshaStatus());
        model.addAttribute("remainSeconds",vo.getRemainSeconds());
        SpringWebContext ctx = new SpringWebContext(request,response,request.getServletContext(),request.getLocale(),model.asMap(),applicationContext);
        if(user == null){
            return  thymeleafViewResolver.getTemplateEngine().process(Const.page.LOGIN_PAGE,ctx);
        }
        // 从缓存里面去取页面
        String html = redisService.get(GoodsKey.getGoodsDetailKeyPage,Const.page.GOODS_DETAIL+goodsId);
        if(StringUtils.isNotEmpty(html)){
            return html;
        }
        // 没有取到页面，手动渲染页面
        html = thymeleafViewResolver.getTemplateEngine().process(Const.page.GOODS_DETAIL,ctx);
        if(StringUtils.isNotEmpty(html)){
            // 得到渲染后的模板，保存到redis里面,缓存60秒
            redisService.setEx(GoodsKey.getGoodsDetailKeyPage,Const.page.GOODS_DETAIL+goodsId,html,GoodsKey.getGoodsDetailKeyPage.expireSeconds());
        }
        return html;
    }


    /**
     * 秒杀详情,页面静态化
     * @param goodsId
     * @param user
     * @return
     */
    @RequestMapping(value = "detail.do/{goodsId}")
    @ResponseBody
    public Result detailPage(@PathVariable long goodsId, SeckillUser user){
        if(user==null){
          return Result.coderMsg(CodeMsg.SESSION_ERROR);
        }
        GoodsVo goods = goodsService.getGoodsVoByGoodsId(goodsId);
        long startAt = goods.getStartDate().getTime();
        long endAt = goods.getEndDate().getTime();
        GoodsDetailVo vo = getStatus(startAt,endAt);
        vo.setUser(user);
        vo.setGoodsVo(goods);
        return Result.success(vo);
    }

    /**
     * 秒杀是否开始
     * @param startAt
     * @param endAt
     * @return
     */
    private GoodsDetailVo getStatus(long startAt,long endAt){
        GoodsDetailVo vo = new GoodsDetailVo();
        long now = System.currentTimeMillis();
        if(startAt > now){
            //秒杀未开始，倒计时
            vo.setMiaoshaStatus(0);
            vo.setRemainSeconds((int)((startAt-now)/1000));
        }else if(endAt < now){
            //秒杀已经结束
            vo.setRemainSeconds(-1);
            vo.setMiaoshaStatus(2);
        } else{
            //秒杀正在进行
            vo.setMiaoshaStatus(1);
        }
        return  vo;
    }

}
